package com.netease.nim.uikit.session.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dididoctor.patient.Bean.DiaeasesLitapal;
import com.netease.nim.uikit.MV.ConstantValueWYY;
import com.netease.nim.uikit.R;
import com.netease.nim.uikit.cache.FriendDataCache;
import com.netease.nim.uikit.session.SessionCustomization;
import com.netease.nim.uikit.session.actions.ImageBasePresenter;
import com.netease.nim.uikit.session.constant.Extras;
import com.netease.nim.uikit.session.fragment.MessageFragment;
import com.netease.nim.uikit.uinfo.UserInfoHelper;
import com.netease.nim.uikit.uinfo.UserInfoObservable;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.Observer;
import com.netease.nimlib.sdk.msg.MsgServiceObserve;
import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum;
import com.netease.nimlib.sdk.msg.model.CustomNotification;

import java.io.Serializable;
import java.util.List;


/**
 * 点对点聊天界面
 * <p/>
 * Created by huangjun on 2015/2/1.
 */
public class P2PMessageActivity extends BaseMessageActivity {

    private boolean isResume = false;
    private String start;//设置聊天界面变化的状态  1聊天 2进行评价 3 继续聊天
    private String recid;//问诊表表的ID
    private String hosId;//医院的ID
    private String userid;//用户的ID
    private String token;//token
    private String doctorid;//医院的ID
    private String  accId;//聊天人的云信ID
    private String  name;//与谁聊天
    private String  sign;//是否签约，在立即咨询处使用
    private ImageBasePresenter presenter;
    public static void start(Context context, String contactId, SessionCustomization customization) {
        Intent intent = new Intent();
        intent.putExtra(Extras.EXTRA_ACCOUNT, contactId);
        intent.putExtra(Extras.EXTRA_CUSTOMIZATION, customization);
        intent.setClass(context, P2PMessageActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        context.startActivity(intent);
    }
    //recid问诊表表的ID   disid疾病的id  start,recid,hosId,userid,token  //doctorid医院的ID    accId聊天人的云信ID
    public static void start(Context context, String contactId, SessionCustomization customization,String start,String recid,String hosId,String userid ,String token,String doctorid,String accId,String name,String sign) {
        Intent intent = new Intent();
        intent.putExtra(Extras.EXTRA_ACCOUNT, contactId);
        intent.putExtra(Extras.EXTRA_CUSTOMIZATION, customization);
        intent.setClass(context, P2PMessageActivity.class);
//        FLAG_ACTIVITY_SINGLE_TOP
        intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
        intent.putExtra("start", start);
        intent.putExtra("recid", recid);
        intent.putExtra("hosId",hosId);
        intent.putExtra("userid",userid);
        intent.putExtra("token",token);
        intent.putExtra("doctorid", doctorid);
        intent.putExtra("accId",accId);
        intent.putExtra("name", name);
        intent.putExtra("sign", sign);
        context.startActivity(intent);
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 单聊特例话数据，包括个人信息，
        requestBuddyInfo();
        registerObservers(true);

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        Intent intentfail = new Intent();
        intentfail.setAction(ConstantValueWYY.PICK_IMAGE_RECEIVE);
        intentfail.putExtra("End",true);
        P2PMessageActivity.this.sendBroadcast(intentfail);
        registerObservers(false);

    }

    @Override
    protected void onResume() {
        super.onResume();
        isResume = true;
    }

    @Override
    protected void onStop() {
        super.onStop();
        isResume = false;
    }

    private void requestBuddyInfo() {
        if (!"".equals(sessionId) && sessionId !=null){
            setTitle(UserInfoHelper.getUserTitleName(sessionId, SessionTypeEnum.P2P));
        }
    }

    private void registerObservers(boolean register) {
        if (register) {
            registerUserInfoObserver();
        } else {
            unregisterUserInfoObserver();
        }
        NIMClient.getService(MsgServiceObserve.class).observeCustomNotification(commandObserver, register);
        FriendDataCache.getInstance().registerFriendDataChangedObserver(friendDataChangedObserver, register);
    }

    FriendDataCache.FriendDataChangedObserver friendDataChangedObserver = new FriendDataCache.FriendDataChangedObserver() {
        @Override
        public void onAddedOrUpdatedFriends(List<String> accounts) {
            setTitle(UserInfoHelper.getUserTitleName(sessionId, SessionTypeEnum.P2P));
        }

        @Override
        public void onDeletedFriends(List<String> accounts) {
            setTitle(UserInfoHelper.getUserTitleName(sessionId, SessionTypeEnum.P2P));
        }

        @Override
        public void onAddUserToBlackList(List<String> account) {
            setTitle(UserInfoHelper.getUserTitleName(sessionId, SessionTypeEnum.P2P));
        }

        @Override
        public void onRemoveUserFromBlackList(List<String> account) {
            setTitle(UserInfoHelper.getUserTitleName(sessionId, SessionTypeEnum.P2P));
        }
    };

    private UserInfoObservable.UserInfoObserver uinfoObserver;

    private void registerUserInfoObserver() {
        if (uinfoObserver == null) {
            uinfoObserver = new UserInfoObservable.UserInfoObserver() {
                @Override
                public void onUserInfoChanged(List<String> accounts) {
                    if (accounts.contains(sessionId)) {
                        requestBuddyInfo();
                    }
                }
            };
        }

        UserInfoHelper.registerObserver(uinfoObserver);
    }

    private void unregisterUserInfoObserver() {
        if (uinfoObserver != null) {
            UserInfoHelper.unregisterObserver(uinfoObserver);
        }
    }

    /**
     * 命令消息接收观察者
     */
    Observer<CustomNotification> commandObserver = new Observer<CustomNotification>() {
        @Override
        public void onEvent(CustomNotification message) {
            if (!sessionId.equals(message.getSessionId()) || message.getSessionType() != SessionTypeEnum.P2P) {
                return;
            }
//            showCommandMessage(message);
        }
    };

    protected void showCommandMessage(CustomNotification message) {
        if (!isResume) {
            return;
        }

        String content = message.getContent();
        try {
            JSONObject json = JSON.parseObject(content);
            int id = json.getIntValue("id");
            if (id == 1) {
                // 正在输入
//                Toast.makeText(P2PMessageActivity.this, "对方正在输入...", Toast.LENGTH_LONG).show();
            } else {
//                Toast.makeText(P2PMessageActivity.this, "command: " + content, Toast.LENGTH_SHORT).show();
            }

        } catch (Exception e) {

        }
    }

    @Override
    protected MessageFragment fragment() {
        Bundle arguments = getIntent().getExtras();
        arguments.putSerializable(Extras.EXTRA_TYPE, SessionTypeEnum.P2P);
        //recid问诊表表的ID   disid疾病的id
        start = getIntent().getStringExtra("start");
        recid = getIntent().getStringExtra("recid");
        hosId = getIntent().getStringExtra("hosId");
        userid = getIntent().getStringExtra("userid");
        token = getIntent().getStringExtra("token");
        //doctorid 医院的ID    accId 聊天人的云信ID
        doctorid = getIntent().getStringExtra("doctorid");
        accId = getIntent().getStringExtra("accId");
        name = getIntent().getStringExtra("name");
        sign = getIntent().getStringExtra("sign");
        presenter = new  ImageBasePresenter(P2PMessageActivity.this);
        presenter.initBroadcast();

        //设置聊天界面变化的状态  1聊天 2进行评价 3 继续聊天
//        start,recid,hosId,userid,token
        MessageFragment fragment = new MessageFragment(presenter,start,recid,hosId,userid,token,doctorid,accId,name,sign);
        fragment.setArguments(arguments);
        fragment.setContainerId(R.id.message_fragment_container);

        return fragment;
    }

    public void back(View view) {
        finish();
    }

    @Override
    protected int getContentViewId() {
        return R.layout.nim_message_activity;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        Intent intentfail = new Intent();
        intentfail.setAction(ConstantValueWYY.PICK_IMAGE_RECEIVE);
        intentfail.putExtra("requestCode", requestCode);
        Bundle bundle = new Bundle();
        bundle.putParcelable("data",data);
        intentfail.putExtras(bundle);
        P2PMessageActivity.this.sendBroadcast(intentfail);
    }


}
